import json
import logging

logger = logging.getLogger('Record')

class Recorder(object):
    
    def __init__(self):
        self.record_list = []
        self.packet_idx = 0
        self.pending_packets = []

    def record_packet_send(self, src_node, send_time, tag):
        self.pending_packets.append({
            'src': src_node.id,
            'send_time': send_time,
            'tag': tag
        })
        metadata = {
            'send_time': send_time
        }
        logger.debug(f'{send_time:.6f} {src_node.id} pending packet {send_time:.6f} tag:{tag}')
        return metadata

    def record_packet_recv(self, dst_node, arrive_time, metadata):
        # 更新pending packets，删除历史
        self.pending_packets = [p for p in self.pending_packets if p['send_time'] >= metadata['send_time']]
        logger.debug(f'{arrive_time:.6f} {dst_node.id} pendings:{len(self.pending_packets)}')
        for p in self.pending_packets:
            if p['send_time'] == metadata['send_time']:
                self.record_list.append({
                    'type': 'packet',
                    'id': self.packet_idx,
                    'src': p['src'],
                    'dst': dst_node.id,
                    'send_time': p['send_time'],
                    'arrive_time': arrive_time,
                    'tag': p['tag']
                })
                logger.debug(f'{arrive_time:.6f} {dst_node.id} record packet {self.packet_idx}')
                self.packet_idx += 1
                break
        
    def record_postion(self, node):
        pos = node.position
        self.record_list.append({
            'type': 'pos',
            'node': node.id,
            'time': node.env.now,
            'pos': [pos.x, pos.y, pos.z]
        })

    def save(self, filepath):
        with open(filepath, "w") as f:
            json.dump(self.record_list, f, indent=2)



recorder = Recorder()